from model.Record import Record
from controller.Base import BaseHandler
from tornado import gen
from model.Course import Course

from io import BytesIO

import xlsxwriter

# m : method
# /api/student
class RecordHandler(BaseHandler):
    @gen.coroutine
    def get(self):
        try:
            method = self.get_argument("m")
        except Exception as e:
            return self.write(self.response_code.PARAM_NOT_COMPLETE)

        # 类型检查
        if not method.isdigit():
            return self.write(self.response_code.PARAM_TYPE_BIND_ERROR)
        t = self.response_code.SUCCESS.copy()
        method = int(method)

        if method == 0:
            # 学生可用，按课程查看
            c_id = self.get_argument("cid")
            s_id = self.session.get("id")
            data = yield Record.get_by_student_class(s_id, c_id)

        elif method == 1:
            # 教师可用,按课程,学号,日期,节次查询 某学生出勤情况
            c_id = self.get_argument("cid", "")
            s_id = self.get_argument("id", "")
            date = self.get_argument("date", "")
            number = self.get_argument("number", "")
            t_id = self.session.get("id")
            data = yield Record.get_by_teacher(t_id, c_id, s_id, date, number)

        else:
            return self.write(self.response_code.PARAM_IS_INVALID)
        t["data"] = data
        t["total"] = len(data)
        return self.write(t)

    @gen.coroutine
    def post(self):
        pass

    @gen.coroutine
    def put(self):
        try:
            r_id = self.get_argument("rid")
            status = self.get_argument("status")
        except Exception as e:
            return self.write(self.response_code.PARAM_NOT_COMPLETE)
        # 类型检查
        if not r_id.isdigit() or not status.isdigit() :
            return self.write(self.response_code.PARAM_TYPE_BIND_ERROR)
        result = yield Record.update_state(r_id, status)
        if result:
            self.write(self.response_code.SUCCESS)
        else:
            self.write(self.response_code.DATA_IS_WRONG)

    @gen.coroutine
    def delete(self):
        pass


class RecordDownloadHandler(BaseHandler):
    @gen.coroutine
    def get(self):
        # 教师可用,将本人授课数据导出
        t_id = self.session.get("id")
        f = BytesIO()
        workbook = xlsxwriter.Workbook(f)
        courses = yield Course.get_by_tid(t_id)
        print(courses)
        for course in courses:
            worksheet = workbook.add_worksheet(course['cname'])
            worksheet.set_column(1, 1, 15)
            worksheet.write_row(0, 0, ("姓名", "学号", "出勤次数", "旷课次数", "请假次数"))
            data = yield Record.get_by_teacher_summary(t_id, course['cid'])
            for index, stu_record in enumerate(data, start=1):
                # record = {name, id, attend_count, absent_count, qj_count}
                worksheet.write_row(index, 0, stu_record.values())
        workbook.close()
        self.set_header("Content-type", "application/octet-stream")
        return self.write(f.getvalue())
